package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.LOGIN_USER;

public class RefreshInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /* 获取session
        HttpSession session = request.getSession();*/
        //获取token,并获取用户信息
        String token = request.getHeader("authorization");
        Map<Object, Object> userDtoMap = stringRedisTemplate.opsForHash()
                .entries("login:token:" + token);
        if (userDtoMap.isEmpty()) {
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userDtoMap, new UserDTO(), false);
        //从session
//        Object user = session.getAttribute("user");
        //存在，存入threadLocal中
        UserHolder.saveUser(userDTO);
        stringRedisTemplate.opsForHyperLogLog().add("viewPerson",userDTO.getId().toString());
        stringRedisTemplate.expire(LOGIN_USER + token,30, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //销毁数据，防止用户信息泄露
        UserHolder.removeUser();
    }
}
